package com.mo.xi.ge.info.loc

import android.location.Location
import android.location.LocationManager


/**
 * data:2024/01/25
 */
internal object CacheLocation {

    private const val LATITUDE = "keyLatitude"
    private const val LONGITUDE = "keyLongitude"
    private val mSharedPreference by lazy {
        LocationWrapper.applicationContext?.getSharedPreferences(
            "locationInfo",
            android.content.Context.MODE_PRIVATE
        )
    }

    private var mLatitude: String? = null
        get() = mSharedPreference?.getString(
            LATITUDE,
            ""
        ).orEmpty()
        set(value){
            field = value
            mSharedPreference?.edit()?.putString(
                LATITUDE, value
            )?.apply()
        }

    private var mLongitude: String? = null
        get() = mSharedPreference?.getString(
            LONGITUDE,
            ""
        ).orEmpty()
        set(value) {
            field = value
            mSharedPreference?.edit()?.putString(
                LONGITUDE, value
            )?.apply()
        }


    fun getCache(): Location? {
        val cacheLatitude = mLatitude
        val cacheLongitude = mLongitude
        if (cacheLatitude.isNullOrEmpty() || cacheLongitude.isNullOrEmpty()) {
            return null
        }
        var resultLocation: Location? = null
        try {
            resultLocation = Location(LocationManager.NETWORK_PROVIDER).apply {
                latitude = cacheLatitude.toDoubleOrNull() ?: 0.0
                longitude = cacheLongitude.toDoubleOrNull() ?: 0.0
            }
        } catch (e: Exception) {
        }
        return resultLocation
    }

    fun updateCache(location: Location) {
        location.apply {
            mLatitude = latitude.toString()
            mLongitude = longitude.toString()
        }
    }
}
